#include "Player.h"

Player::Player( )
{
	srand( unsigned( time(NULL) ) ) ;

	m_PosX = rand() % 8 ;
	m_PosY = rand() % 8 ;

	m_LastPosX = m_PosX ;
	m_LastPosY = m_PosY ;

	m_QuadPosX = rand() % 8 ;
	m_QuadPosY = rand() % 8 ;

	m_state = IDLE ;

	m_energy = 3000 ;
	m_shields = 2500 ;
	m_missiles = 10 ;

	m_dead = false ;
}

Player::~Player( )
{

}

void Player::SetTarget( int x, int y )
{
	m_TargetX = x ;
	m_TargetY = y ;
}

void Player::Move( Quadrant* currQuad )
{
	//calculates the difference between x and y sectors (absolute value)
	int diffX, diffY ;

	//lose energy for every step
	m_energy -= 10 ;

	//finds the difference in x axis
	diffX = m_PosX - m_TargetX ;

	diffY = m_PosY - m_TargetY ;

	if( diffX < 0 )
		diffX = -diffX ;

	if( diffY < 0 )
		diffY = -diffY ;

	//changes the state back to IDLE if target sector is already reached
	if( diffX == 0 && diffY == 0 )
		m_state = IDLE ;
	//otherwise, it will move towards the target sector directly based on largest difference
	else
	{
		//move horizontally
		if( diffX >= diffY )
		{
			m_LastPosX = m_PosX ;

			if( m_PosX > m_TargetX )
				m_PosX-- ;
			else
				m_PosX++ ;

		}
		//move vertically
		else if( diffY > diffX )
		{
			m_LastPosY = m_PosY ;

			if( m_PosY > m_TargetY )
				m_PosY-- ;
			else
				m_PosY++ ;
		}
	}

	cout << "Player has moved to sector " << m_PosX << ", " << m_PosY << endl ;
}

void Player::ShiftBack( )
{
	m_PosX = m_LastPosX ;
	m_PosY = m_LastPosY ;

	cout << "Player has ran into something. Moving back" << endl ;
}

void Player::Warp( int x, int y )
{
	m_QuadPosX = x ;
	m_QuadPosY = y ;
}

void Player::DamagePlayer( int enemyHealth, int distance )
{
	int damage = enemyHealth + ( distance * (rand() % 2 + 2) ) ;
	cout << "Player takes " << damage << " damage to shields." << endl ;
	
	if( m_shields > damage )
	{
		m_shields -= damage ;
	}
	else
	{
		m_dead = true ;
		cout << "Player has died." << endl ;
	}
}

void Player::Dock( )
{
	m_energy = 3000 ;
	m_shields = 2500 ;
	m_missiles = 10 ;
}

bool Player::Collision( Quadrant* currQuad )
{
	if( currQuad->GetSector( m_PosX, m_PosY ) == STAR )
	{
		ShiftBack( ) ;
		m_shields -= (rand() % 90 + 10) ;
		return true ;
	}
	else if( currQuad->GetSector( m_PosX, m_PosY ) == ENEMY )
	{
		ShiftBack( ) ;
		m_shields -= (rand() % 40 + 10) ;
		return true ;
	}

	return false ;
}

void Player::FireMissile( int x, int y )
{
	m_Missile = new Missile( ) ; 
	m_Missile->Init(  m_PosX, m_PosY, m_TargetX, m_TargetY ) ;
}